<template>
  <div class="receipt-details">
    <!-- 报表主体内容 -->
    <el-card shadow="hover" class="main-card">
      <!-- 报表工具栏 -->
      <div class="report-toolbar">
        <div class="toolbar-left">
          <el-radio-group v-model="viewType" size="small">
            <el-radio-button :value="'all'">全部收款</el-radio-button>
            <el-radio-button :value="'cash'">现金</el-radio-button>
            <el-radio-button :value="'wechat'">微信</el-radio-button>
            <el-radio-button :value="'alipay'">支付宝</el-radio-button>
            <el-radio-button :value="'card'">银行卡</el-radio-button>
          </el-radio-group>
        </div>
        <div class="toolbar-right">
          <el-button size="small" @click="refreshData">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
      </div>

      <!-- 报表说明 -->
      <div class="note-content compact-note">
        <el-tag type="info" effect="plain" size="small">
          <i class="el-icon-info"></i> 本报表显示{{ formatDate(props.dateRange[0]) }} 至 {{ formatDate(props.dateRange[1]) }}期间的收款记录
        </el-tag>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :summary-method="getSummaries"
        show-summary
        size="small"
        :row-class-name="tableRowClassName"
        height="calc(100vh - 300px)"
      >
        <el-table-column prop="receiptId" label="单号" min-width="120" />
        <el-table-column prop="type" label="账目名称" min-width="100">
          <template #default="scope">
            <el-tag :type="getReceiptTagType(scope.row.type)" size="small">
              {{ getReceiptTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentType" label="付款方式" min-width="90">
          <template #default="scope">
            <el-tag size="small" effect="plain">{{ getPaymentTypeName(scope.row.paymentType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" min-width="100" align="right">
          <template #default="scope">
            <span :class="{ 'negative-amount': scope.row.amount < 0, 'positive-amount': scope.row.amount > 0 }">
              {{ formatCurrency(scope.row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="营业日" min-width="90" />
        <el-table-column prop="time" label="操作时间" min-width="120" />
        <el-table-column prop="customerName" label="顾客名称" min-width="100" />
        <el-table-column prop="operatorName" label="操作员" min-width="90" />
        <el-table-column prop="shift" label="班次" min-width="70">
          <template #default="scope">
            <el-tag size="small" effect="plain" type="info">{{ getShiftName(scope.row.shift) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storeName" label="渠道" min-width="90" />
        <el-table-column prop="remark" label="备注" min-width="130" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { formatCurrency, formatDate } from '@/utils/formatters';
import reportApi from '@/api/reports';

const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  },
  filterParams: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['refresh']);

// 状态变量
const viewType = ref('all');
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 计算属性 - 表格数据
const tableData = computed(() => {
  const data = props.reportData.items || [];
  if (viewType.value === 'all') {
    return data;
  }
  
  // 根据视图类型过滤数据
  return data.filter(item => item.paymentType === viewType.value);
});

// 刷新数据
const refreshData = () => {
  emit('refresh', {
    page: currentPage.value,
    pageSize: pageSize.value,
    viewType: viewType.value
  });
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  pageSize.value = size;
  refreshData();
};

// 处理当前页变更
const handleCurrentChange = (page) => {
  currentPage.value = page;
  refreshData();
};

// 获取收款类型名称
const getReceiptTypeName = (type) => {
  const types = {
    'sale': '销售收款',
    'refund': '退款',
    'recharge': '会员充值',
    'adjustment': '收款调整',
    'ar': 'AR账款',
    'ar-refund': 'AR退款'
  };
  
  return types[type] || type;
};

// 获取收款类型标签样式
const getReceiptTagType = (type) => {
  const types = {
    'sale': 'success',
    'refund': 'danger',
    'recharge': 'warning',
    'adjustment': 'info',
    'ar': 'primary',
    'ar-refund': 'danger'
  };
  
  return types[type] || '';
};

// 获取支付方式名称
const getPaymentTypeName = (type) => {
  const types = {
    'cash': '现金',
    'wechat': '微信',
    'alipay': '支付宝',
    'card': '银行卡',
    'member': '会员卡',
    'coupon': '优惠券',
    'mixed': '混合支付'
  };
  
  return types[type] || type;
};

// 获取班次名称
const getShiftName = (shift) => {
  const shifts = {
    'morning': '早班',
    'middle': '中班',
    'evening': '晚班'
  };
  
  return shifts[shift] || shift;
};

// 计算表格合计行
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    
    if (column.property === 'amount') {
      const values = data.map(item => Number(item.amount));
      const total = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + value;
        } else {
          return prev;
        }
      }, 0);
      
      sums[index] = formatCurrency(total);
    } else {
      sums[index] = '';
    }
  });
  
  return sums;
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.amount < 0) {
    return 'negative-row';
  }
  return '';
};

// 监听报表数据变化
watch(() => props.reportData, (newData) => {
  if (newData && newData.total !== undefined) {
    total.value = newData.total;
  }
}, { deep: true });

// 监听视图类型变化
watch(viewType, () => {
  currentPage.value = 1; // 重置为第一页
  refreshData();
});

// 组件挂载时初始化
onMounted(() => {
  // 设置初始视图类型（可能从筛选条件中获取）
  if (props.filterParams.receiptType) {
    viewType.value = props.filterParams.receiptType;
  }
  
  // 如果报表数据中包含分页信息，更新分页状态
  if (props.reportData.total !== undefined) {
    total.value = props.reportData.total;
  }
});
</script>

<style scoped>
.receipt-details {
  margin-bottom: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.report-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.toolbar-left, .toolbar-right {
  display: flex;
  align-items: center;
}

.compact-note {
  margin-bottom: 10px;
  font-size: 12px;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-table th) {
  padding: 8px 0;
}

:deep(.el-table td) {
  padding: 6px 0;
}

:deep(.negative-row) {
  background-color: #fef0f0 !important;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.negative-amount {
  color: #F56C6C;
  font-weight: bold;
}

.positive-amount {
  color: #67C23A;
  font-weight: bold;
}

@media screen and (max-width: 768px) {
  .report-toolbar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .toolbar-left, .toolbar-right {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style> 